<template>
 <div class="finger-touch" @touchstart="move" @touchmove="move">
   <div class="box" ref="boxRef" >

   </div>
 </div>
</template>

<script lang='ts'>
import { Vue, Options } from 'vue-property-decorator';
interface Pos{
  x: number;
  y: number;
}
// @Options 装饰器可以使类成为 Vue 组件
@Options({ components: {

} })
export default class FingerTouch extends Vue {
  private rect: null |  DOMRect= null;
  private endTo: Pos = { x: 0, y: 0 };
  private current: Pos = { x: 0, y: 0 };
  private timer: null | number= null;


  public move(e: TouchEvent) {
    // this.endTo = {
    //   x: e.touches[0].pageX - this.rect!.x,
    //   y: e.touches[0].pageY - this.rect!.y,
    // };
    this.endTo.x =  e.touches[0].pageX - this.rect!.x;
    this.endTo.y =  e.touches[0].pageY - this.rect!.y;
    // console.log(e.touches[0]);
    if (!this.timer) {
      this.play();
    }
  }
  private play() {
    console.log(1111);
    if (Math.abs(this.endTo.x - this.current.x) > 0.1 || Math.abs(this.endTo.y - this.current.y) > 0.1) {
      // 希望浏览器重绘之前执行的动画
      this.current.x += (this.endTo.x - this.current.x) / 10;
      this.current.y += (this.endTo.y - this.current.y) / 10;
      // eslint-disable-next-line max-len
      // (this.$refs.boxRef as HTMLDivElement).style.transform = `translate(${this.endTo.x - this.current.x}px, ${this.endTo.y - this.current.y}px)`;
      (this.$refs.boxRef as HTMLDivElement).style.transform = `translate(${this.current.x}px, ${this.current.y}px)`;
      this.timer = window.requestAnimationFrame(this.play);
    } else {
      // window.cancelAnimationFrame(this.timer!);
      this.timer = null;
      console.log(2222);
    }
    // this.timer = window.requestAnimationFrame(this.play);
  }
  public mounted() {
    this.rect = (this.$el as HTMLDivElement).getBoundingClientRect();
    console.log(this.rect);
  }
  public unmounted() { // 钩子函数销毁
    window.cancelAnimationFrame(this.timer!);
    this.timer = null;
  }
};
</script>

<style lang='postcss' scoped>

.finger-touch{
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: grey;
  touch-action: none;
  overflow: hidden;
  .box{
    position: absolute;
    top:0;
    left:0;
    width: 30px;
    height: 30px;
    margin:-15px;
    background-color: red;
  }
}

</style>
